import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
    state: () => {
        // 尝试从localStorage恢复用户信息
        let user = null;
        try {
            const storedUser = localStorage.getItem('studentUserInfo');
            if (storedUser) {
                user = JSON.parse(storedUser);
                console.log('从localStorage恢复用户信息:', user);
            }
        } catch (error) {
            console.error('恢复用户信息失败:', error);
        }

        return {
            user,
            token: localStorage.getItem('token') || null
        }
    },
    actions: {
        login(token, user) {
            this.token = token;
            this.user = user;
            if (token) localStorage.setItem('token', token);
            if (user) localStorage.setItem('studentUserInfo', JSON.stringify(user));
        },
        setUser(user) {
            this.user = user;
            if (user) {
                localStorage.setItem('studentUserInfo', JSON.stringify(user));
                console.log('用户信息已保存:', user);
            }
        },
        logout() {
            this.token = null;
            this.user = null;
            localStorage.removeItem('token');
            localStorage.removeItem('studentUserInfo');
        }
    }
});
